from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect

from ff_app.forms import LoginForm, FarmerFileForm
from ff_app.models import FarmerFile


# Create your views here.

def login(req):
    if req.method == 'GET':
        context = { }
        context['form'] = LoginForm()
        return render(req, 'login.html', context)
    elif req.method == 'POST':
        login_form = LoginForm(req.POST) # 使用表单数据创建Form对象
        if login_form.is_valid():
            data = login_form.cleaned_data
            user = auth.authenticate(username=data['username'],
                                     password=data['password']) # 不匹配返回None
            if user:
                auth.login(req, user)
                return redirect('farmer_file_form')
            else:
                login_form.add_error('username', '登录密码错误')
                return render(req, 'login.html', {'form': login_form})
        else:
            return render(req, 'login.html', {'form': login_form})

def logout(req):
    auth.logout(req)
    return redirect('login')

@login_required(login_url='/ff/login/')
def farmer_file_form(req):
    farmers = FarmerFile.objects.filter(farmer_id=req.user.id)
    if farmers.count() > 0: # 已提交
        if farmers.first().status == 0:  # 未审核状态
            return HttpResponse("您已提交过档案，请耐心等待银行客户经理的审核结果。")
        if farmers.first().status == 1:  # 已审核状态
            return HttpResponse("恭喜您，您的档案已审核通过。")
        if farmers.first().status == -1:  # 未通过审核状态
            return HttpResponse("非常抱歉，您的档案未通过审核。")

    if req.method == 'GET':
        context = {'form': FarmerFileForm()}
        return render(req, 'farmer_file_form.html', context)
    elif req.method == 'POST':
        farmer_file_form = FarmerFileForm(req.POST)  # 使用表单数据创建Form对象
        if farmer_file_form.is_valid():
            farmer_file = farmer_file_form.save(commit=False)
            farmer_file.farmer = req.user
            farmer_file.save()
            return HttpResponse("已成功提交农户档案，等待银行客户经理审核。")
        else:
            return render(req, 'farmer_file_form.html', {'form': farmer_file_form})
